import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import App from './App'
/*引入axios*/
import axios from 'axios'
//设置请求的公共前缀
axios.defaults.baseURL="http://localhost";
//请求的公共前缀
/*给vue类型添加$http原型，方便在组件中获取axios对象*/
Vue.prototype.$http = axios;

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
//import './assets/theme/theme-green/index.css'

//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
//准备的路由，路径映射组件代码放到此文件中
import routes from './routes'

import 'font-awesome/css/font-awesome.min.css'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

//创建路由
const router = new VueRouter({
    routes
})

/*axios前置拦截器*/
axios.interceptors.request.use(config => {
    //携带token
    let token = localStorage.getItem("token");
    if (token) {
        //在头信息中添加token
        config.headers['token'] = token;
    }
    return config;
}, error => {
    Promise.reject(error);
});

//axios后置拦截器
axios.interceptors.response.use(result => {
    let {success, msg} = result.data;
    if(!success && msg === "noLogin"){
        //清空本地存储
        localStorage.removeItem("token");
        localStorage.removeItem("loginUser");
        router.push({ path: '/login' });
    }
    return result;
}, error => {
    Promise.reject(error);
});



//路由的拦截器
router.beforeEach((to, from, next) => {
  //如果你访问的目标资源是/login 或者/shopRegister 我就直接放行
  if(to.path=="/login"||to.path=="/shopRegister"){
      //放行让其执行目标资源
      next();
  }else{
    //如果是访问其他资源，我就要获取token是否有值
      var token = localStorage.getItem("token");
      //如果token有值，就直接放行
      if(token){
          next();
      }else{
        //那就直接跳转到登录界面
          next({path: '/login'});
      }
  }
})

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

